import { Upload, UploadProps, message } from "antd";
import { useState } from "react";
import ImgCrop from "antd-img-crop";
import {
  LoadingOutlined,
  OneToOneOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import admin_config from "@/config/admin_config";

export default function UploadOne({
  onChange,
  value = "",
  desc = "",
  aspect = 1,
}: {
  onChange?: Function;
  value?: string;
  desc?: string;
  aspect?: number;
}) {
  const [imgs, setImgs] = useState(value);
  const [loading, setLoading] = useState(false);
  const [temp, setTemp] = useState("");
  const handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      const {
        file: { response },
      } = info;
      if (response.code === 200) {
        let url = response.data;
        setImgs(url);
        onChange?.(url);
      } else {
        message.error("上传失败");
      }
      setLoading(false);
    }
  };

  const uploadButton = () => (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );

  return (
    <div>
      <ImgCrop
        showGrid={true}
        // rotationSlider
        aspect={aspect}
        minZoom={0.4}
        cropperProps={{ restrictPosition: false } as any}
        // cropperProps={{}}
        modalProps={
          {
            width: "50%",
          } as any
        }
        aspectSlider
      >
        <Upload
          name="file"
          listType="picture-card"
          className="flex flex-col"
          accept="image/png, image/jpeg,image/jpg"
          showUploadList={false}
          action={admin_config.uploadImg}
          // beforeUpload={(file) => {
          //   return new Promise((resolve) => {
          //     const reader = new FileReader();
          //     reader.readAsDataURL(file);
          //     reader.onload = () => {
          //       // console.log();
          //       setTemp(reader.result as string);
          //       resolve(false);
          //     };
          //   });
          // }}
          onChange={(e) => handleChange(e)}
        >
          {imgs ? (
            <img src={imgs} alt="avatar" style={{ width: "100%" }} />
          ) : (
            uploadButton()
          )}
        </Upload>
      </ImgCrop>
      <div className="text-blue-500">{desc}</div>
    </div>
  );
}
